package syllabus.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import syllabus.dao.PSyllabusMapper;
import syllabus.model.Criteria;
import syllabus.model.PSyllabus;
import syllabus.service.PSyllabusService;

@Service
public class PSyllabusServiceImpl implements PSyllabusService {
    @Autowired
    private PSyllabusMapper pSyllabusMapper;

    private static final Logger logger = LoggerFactory.getLogger(PSyllabusServiceImpl.class);

    public int countByExample(Criteria example) {
        int count = this.pSyllabusMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    public PSyllabus selectByPrimaryKey(Integer id) {
        return this.pSyllabusMapper.selectByPrimaryKey(id);
    }

    public List<PSyllabus> selectByExample(Criteria example) {
        return this.pSyllabusMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(Integer id) {
        return this.pSyllabusMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(PSyllabus record) {
        return this.pSyllabusMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(PSyllabus record) {
        return this.pSyllabusMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(Criteria example) {
        return this.pSyllabusMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(PSyllabus record, Criteria example) {
        return this.pSyllabusMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(PSyllabus record, Criteria example) {
        return this.pSyllabusMapper.updateByExample(record, example);
    }

    public int insert(PSyllabus record) {
        return this.pSyllabusMapper.insert(record);
    }

    public int insertSelective(PSyllabus record) {
        return this.pSyllabusMapper.insertSelective(record);
    }

	public boolean mergeSyllabus(String kcdm, String merge_kcdm) {
		Criteria c = new Criteria();
		c.put("kcdm", kcdm);
		List<PSyllabus> list = pSyllabusMapper.selectByExample(c);
		if (null == list || list.size() != 1) {
			return false;
		}
		PSyllabus s1 = list.get(0);
		
		c.put("kcdm", merge_kcdm);
		List<PSyllabus> list_merge = pSyllabusMapper.selectByExample(c);
		if (null == list_merge || list_merge.size() != 1) {
			return false;
		}
		PSyllabus s2 = list_merge.get(0);
		String link = s1.getLink();
		String filename = s1.getFilename();
		if(StringUtils.isNotBlank(link) && StringUtils.isNotBlank(filename)){
			s2.setLink(s1.getLink());
			s2.setFilename(s1.getFilename());
			pSyllabusMapper.updateByPrimaryKeySelective(s2);
			return true;
		}
		
		return false;
	}

}